package view;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import options.view.ViewSettings;

import exceptions.SaveErrorException;

public class PopupFrame extends JFrame {
	private static final long serialVersionUID = -7144551651971834140L;
	private JPanel panel = null;
	
	public PopupFrame(JPanel panel) {
		super();
		this.panel = panel;
		
		initialize();
	}
	
	private void initialize() {
		this.setSize(panel.getWidth(), panel.getHeight() + 30);
		this.add(panel, null);
		ViewSettings.getSettings().setIcon(this);
		this.setResizable(false);
		this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
		ViewSettings.getSettings().centerDialog(this);
		this.setVisible(true);
		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if(((OptionPanelInterface) PopupFrame.this.panel).isModified()) {
					int option = JOptionPane.showConfirmDialog(PopupFrame.this, "Salvare le modifiche?", "", JOptionPane.YES_NO_CANCEL_OPTION);
					
					switch(option) {
						case JOptionPane.YES_OPTION:
							System.err.println("SALVARE LE MODIFICHE");
							try {
								((OptionPanelInterface) PopupFrame.this.panel).save();
								PopupFrame.this.dispose();
							} catch (SaveErrorException exc) {
								exc.printStackTrace();
							}
							break;
						case JOptionPane.NO_OPTION: 
							PopupFrame.this.dispose();
							break;
						case JOptionPane.CANCEL_OPTION : case JOptionPane.CLOSED_OPTION: break;
					}
				} else
					PopupFrame.this.dispose();
			}
		});
	}

}
